/**
 * Copyright (C), 2015-2021, 开度
 * FileName: MyAccessDecisionService
 * Author:   ASUS
 * Date:     2021/4/28 10:16
 * Description: 自定义的权限校验
 * History:
 * <author>          <time>          <version>          <desc>
 * Hezeyu           2021/4/28           1.0              自定义的权限校验
 */
package com.example.spring.security.interceptor.menu;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;

/**
 * 〈自定义的权限校验〉
 *
 * @author ASUS
 * @create 2021/4/28
 * @since 1.0.0
 */
@Slf4j
@Service
public class MyAccessDecisionService implements AccessDecisionManager {
    /**
     *
     *
     * @param authentication 当前用户所具有的权限
     * @param o
     * @param configAttributes 当前访问所需要的权限
     * @return:void
     * @since: 1.0.0
     * @Author:hezeyu
     * @Date: 2021/4/28 10:18
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()) {
            ConfigAttribute ca = iterator.next();
            //当前请求需要的权限
            String needRole = ca.getAttribute();
            //当前用户所具有的权限
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足!");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
